package net.app.help.activities;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import net.app.help.R;
import net.app.help.adapters.ContactsListViewAdapter;
import net.app.help.db.DatabaseAdapter;
import net.app.help.dialogs.AddContactDialog;
import net.app.help.dialogs.AttachMessageDialog;
import net.app.help.model.Contact;
import net.app.help.model.Group;
import net.app.help.model.Message;

import java.util.ArrayList;

public class ContactsActivity extends ActionBarActivity implements AddContactDialog.onConfirmInterface, AttachMessageDialog.onConfirmInterface {

	private DatabaseAdapter da = new DatabaseAdapter(this);

	boolean[] selected;
	private ArrayList<Contact> contacts;
	private ArrayList<Group> groups;
	private ArrayList<Message> messages;

	private Button addContact, delContact, attMessage, remMessage;
	private ListView contactsListView;
	private ContactsListViewAdapter contactsListViewAdapter;

	private AddContactDialog addContactDialog;

	private void setupViews() {
		addContact = (Button) findViewById(R.id.act_con_b_add_contact);
		addContact.setOnClickListener(addContactOnClickListener);
		delContact = (Button) findViewById(R.id.act_con_b_delete_contact);
		delContact.setOnClickListener(deleteContactOnClickListener);
		attMessage = (Button) findViewById(R.id.act_con_b_attach_message);
		attMessage.setOnClickListener(attachMessageOnClickListener);
		remMessage = (Button) findViewById(R.id.act_con_b_remove_message);
		remMessage.setOnClickListener(removeMessageOnClickListener);

		contactsListView = (ListView) findViewById(R.id.act_con_lv_contact_list);
	}

	private void updateAdapter() {
		obtainData();
		contactsListViewAdapter = new ContactsListViewAdapter(contacts, groups, messages, this);
		contactsListView.setAdapter(contactsListViewAdapter);
	}

	private void obtainData() {
		da.openToRead();
		contacts = da.getAllContacts();
		groups = da.getAllGroups();
		messages = da.getAllMessages();
		da.close();
	}

//	public boolean determineVersionIsIceCreamSandwichOrNewer() {
//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//			return true;
//		} else {
//			return false;
//		}
//	}
//
	public void setSupportActionBarLogo() {
		getSupportActionBar().setDisplayShowHomeEnabled(true);
//		getSupportActionBar().setDisplayUseLogoEnabled(true);
//		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setIcon(R.drawable.help_app_icon);
//		getSupportActionBar().setLogo(R.drawable.help_app_icon);
	}

//	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
//	public void setActionBarLogo() {
//		getActionBar().setDisplayShowHomeEnabled(true);
//		getActionBar().setDisplayUseLogoEnabled(true);
//		getActionBar().setIcon(R.drawable.help_app_icon);
//		getActionBar().setLogo(R.drawable.help_app_icon);
//	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contacts);

//		if (determineVersionIsIceCreamSandwichOrNewer()) {
//			setActionBarLogo();
//		} else {
			setSupportActionBarLogo();
//		}

		setupViews();
		//inflate ListView
		updateAdapter();
		selected = contactsListViewAdapter.obtainSelected();
		Log.d("onCreate","selected.length="+selected.length+" selected.toString="+selected.toString());
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		selected = contactsListViewAdapter.obtainSelected();
		Log.d("onRestart","selected.length="+selected.length+" selected.toString="+selected.toString());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_contacts, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		switch (item.getItemId()) {
			case R.id.action_contacts:
				Intent c = new Intent(this, ContactsActivity.class);
				startActivity(c);
				return true;
			case R.id.action_groups:
				Intent g = new Intent(this, GroupsActivity.class);
				startActivity(g);
				return true;
			case R.id.action_messages:
				Intent m = new Intent(this, MessagesActivity.class);
				startActivity(m);
				return true;
			case R.id.action_settings:
				Intent i = new Intent(this, SettingsActivity.class);
				startActivity(i);
				return true;
			case R.id.action_instructions:
				Intent ins = new Intent(this, InstructionsActivity.class);
				startActivity(ins);
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}

	private void addContact(Contact c) {
		da.openToWrite();
		da.addContact(c);
		da.close();
	}

	private void deleteContact(int id) {
		da.openToWrite();
		da.deleteContact(id);
		da.close();
	}

	private View.OnClickListener addContactOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d("addContactOnClickListener", "");
			//open contacts list and allow adding
			addContactDialog = new AddContactDialog();
//			Bundle b = new Bundle();
//			b.putParcelable();
//			addContactDialog.setArguments(b);
			addContactDialog.show(getFragmentManager(), "ADDCONTACTDIALOG TAG");
		}
	};

	private View.OnClickListener deleteContactOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d("removeContactOnClickListener", "");
			//create dialog to delete selected contacts.
			selected = contactsListViewAdapter.obtainSelected();	//pridobi izbrane kontakte
			if (checkIfAtLeastOneSelected()) {
				AlertDialog.Builder builder = new AlertDialog.Builder(ContactsActivity.this);
				builder.setTitle("Confirm deletion");
				builder.setMessage("Do you really want to delete checked contacts from the application?");
				builder.setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						for (int i = 0; i < selected.length; i++) {
							if (selected[i]) {
								Log.d("Deleting contact from DB", "Contact=" + contacts.get(i).toString());
								deleteContact(contacts.get(i).getId());
							}
						}
						updateAdapter();
					}
				});
				builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//nič
					}
				});
				builder.create();
				builder.show();
			} else {
				showAlertDialog("Error", "Contacts are not checked");
			}
		}
	};

	private View.OnClickListener attachMessageOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d("attachMessageOnClickListener", "");
			selected = contactsListViewAdapter.obtainSelected();	//pridobi izbrane kontakte
			ArrayList<Contact> selectedContacts = new ArrayList<Contact>(selected.length);
			if (checkIfAtLeastOneSelected()) {
				for (int i = 0; i < contacts.size(); i++) {
					if (selected[i]) {
						selectedContacts.add(contacts.get(i));
					}
				}
				if (messages.size() > 0) {
					AttachMessageDialog amd = AttachMessageDialog.newInstance(messages, selectedContacts, new ArrayList<Group>(0));
					amd.show(getFragmentManager(), "AttachMessageDialog CONTACTS");
				} else {
					showAlertDialog("Error", "Preset message first");
				}
			/*MORDA VSEENO POTREBNO IMPLEMENTIRATI INTERFACE ZA UPDATEADAPTER*/
			} else {
				showAlertDialog("Error", "Contacts are not checked");
			}
		}
	};

	private View.OnClickListener removeMessageOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d("removeMessageOnClickListener", "");
			selected = contactsListViewAdapter.obtainSelected();	//pridobi izbrane kontakte
//			RemoveMessageFromContactDialog rmfcd = RemoveMessageFromContactDialog.newInstance(selected, contacts, messages);
//			rmfcd.show(getFragmentManager(), "RemoveMessageFromContactDialog");
//			/*MORDA VSEENO POTREBNO IMPLEMENTIRATI INTERFACE ZA UPDATEADAPTER*/
			if (checkIfAtLeastOneSelected()) {
				AlertDialog.Builder builder = new AlertDialog.Builder(ContactsActivity.this);
				builder.setTitle("Confirm message removal");
				builder.setMessage("Do you really want to delete attached message from selected contacts?");
				builder.setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						da.openToWrite();
						for (int i = 0; i < selected.length; i++) {
							if (selected[i] && (contacts.get(i).getId_msg() != 0)) {
								Log.d("Deleting message from selected contact", "Message=KARKOLIŽE" + "Contact=" + contacts.get(i).toString());
								da.removeContactAMessage(contacts.get(i));
							}
						}
						da.close();
						updateAdapter();
					}
				});
				builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//nič
					}
				});
				builder.create();
				builder.show();
			} else {
				showAlertDialog("Error", "Contacts are not checked");
			}
		}
	};

	private boolean checkIfAtLeastOneSelected() {
		int counter = 0;
		for (int i=0; i<selected.length; i++) {
			if (selected[i])
				counter++;
		}
		if (counter != 0)
			return true;
		else
			return false;
	}

	private void showAlertDialog(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(ContactsActivity.this);
		builder.setTitle(title);
		builder.setMessage(message);
//				builder.setIcon(R.drawable.) //ALERT ICON TO BE SET
		builder.setNegativeButton(R.string.button_ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//NIČ
			}
		});
		builder.create();
		builder.show();
	}

	@Override
	public void onConfirmAddContacts(ArrayList<Contact> selectedContacts) {
		for (int i=0; i<selectedContacts.size(); i++) {
			addContact(selectedContacts.get(i));
		}
		Toast.makeText(this, "Contacts added", Toast.LENGTH_SHORT).show();
		updateAdapter();
	}

	@Override
	public void onCancelAddContacts() {
		Toast.makeText(this, "No contacts added", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onConfirmAttachMessage() {
		Toast.makeText(this, "Message attached", Toast.LENGTH_SHORT).show();
		updateAdapter();
	}

	@Override
	public void onCancelAttachMessage() {
		Toast.makeText(this, "No message attached", Toast.LENGTH_SHORT).show();
	}

}
